import {Component, OnInit, DoCheck} from '@angular/core';

// 定义接口
interface TodoItem {
  id: number;
  content: string;
  selected: boolean;
}
@Component({
  selector: 'app-todo-mvc',
  templateUrl: './todo-mvc.component.html',
  styleUrls: ['./todo-mvc.component.less', './todomvc-app.css', './todomvc-common.css']
})
export class TodoMVCComponent implements OnInit, DoCheck {
  public todoList: TodoItem[] = JSON.parse(window.localStorage.getItem('todoList') || '[]');
  public currentItem: any = null;
  public oldItem: any = null;
  public stateList: string[] = ['All', 'Active', 'Completed'];
  public currentState: string = window.localStorage.getItem('currentState') || 'All';
  constructor() { }
  ngOnInit() {
  }
  ngDoCheck(): void {
    window.localStorage.setItem('todoList', JSON.stringify(this.todoList));
    window.localStorage.setItem('currentState', this.currentState);
  }
  get selectedAll () {
    return this.todoList.every(t => t.selected);
  }
  set selectedAll (val) {
    this.todoList.forEach((item) => {
      item.selected = val;
    });
  }
  get list () {
    if (this.currentState === 'All') {
      return this.todoList;
    } else if (this.currentState === 'Active') {
      return this.todoList.filter(t => !t.selected);
    } else {
      return this.todoList.filter(t => t.selected);
    }
  }
  get completedCount () {
    return this.todoList.filter(t => !t.selected).length;
  }
  get selectedSome () {
    return this.todoList.some(t => t.selected);
  }
  addItem(e: any): void {
    if (!e.target.value) {
      return;
    }
    const last: TodoItem = this.todoList[this.todoList.length - 1];
    this.todoList.push({
      id: last ? last.id + 1 : 1,
      content: e.target.value,
      selected: false
    });
    e.target.value = '';
  }
  dblClick(item: TodoItem): void {
    this.currentItem = item;
    this.oldItem = { ...item };
  }
  delList(item: TodoItem): void {
    this.todoList.forEach((t, i) => {
      if (t.id === item.id) {
        this.todoList.splice(i, 1);
      }
    });
  }
  editEnter (item: TodoItem): void {
    this.oldItem = { ...item };
    this.currentItem = {};
  }
  editEsc (item: TodoItem): void {
    item.content = this.oldItem.content;
    this.currentItem = {};
  }
  clearCompleted () {
    this.todoList = this.todoList.filter(t => !t.selected);
  }
  stateChange (item: string): void {
    this.currentState = item;
  }
}
